﻿using Oplaco.Samples.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.Storage.Table.DataServices;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.IO;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using System.Net.Http;
using System.Threading.Tasks;

namespace Oplaco.Samples.WebApi.Providers
{
    public class AzureBlobStorageMultipartProvider : MultipartFileStreamProvider
    {
        private CloudBlobContainer _container;
        private Oplaco.Samples.Repository.ArticleRepository repos;

        public AzureBlobStorageMultipartProvider(CloudBlobContainer container) : base(Path.GetTempPath())
        {
            _container = container;
            Files = new List<FileItem>();
        }

        public List<FileItem> Files { get; set; }

        public override Task ExecutePostProcessingAsync()
        {
            // Upload the files to azure blob storage and remove them from local disk
            foreach (var fileData in this.FileData)
            {
                string fileName = Path.GetFileName(fileData.Headers.ContentDisposition.FileName.Trim('"'));
                // Retrieve reference to a blob
                CloudBlockBlob blockBlob = _container.GetBlockBlobReference(fileName);
                blockBlob.Properties.ContentType = fileData.Headers.ContentType.MediaType;
                using (var fileStream = System.IO.File.OpenRead(fileData.LocalFileName))
                {
                    blockBlob.UploadFromStream(fileStream);
                }
                File.Delete(fileData.LocalFileName);

                FileItem item = new FileItem
                {
                    Id = Guid.NewGuid(),
                    Alias = blockBlob.Name,
                    Url = blockBlob.Uri.AbsoluteUri,
                    LastModified = DateTime.Now,
                    FileType = MultimediaTypeEnum.Orginal,
                    ParentId = Guid.Empty,
                };
                
                Files.Add(item);
            }
            return base.ExecutePostProcessingAsync();
        }
    }
}